import { util, ParamErr, BaseErr, InsideErr } from "utils";
import { getRequest } from "request";
import { decode } from "./parse";
import dingdingTool from "./tool";
import { formatterContent } from "../formatterContent";
// 请求数据
async function requestData(url: string): Promise<[BaseErr?, any?]> {
    return await getRequest(url)(
        {},
        {
            dataType: "",
            headers: {
                DNT: 1,
                Pragma: "no-cache",
            },
            // enableProxy: true,
            // rejectUnauthorized: false,
            // proxy: "http://127.0.0.1:8899",
        }
    );
}

// 处理 结果的 buffer
async function handleResultBuffer(
    buffer: Buffer,
    salt: string,
    secret: string
): Promise<[BaseErr?, any?]> {
    try {
        let decodeBuffer = await decode(buffer, salt, secret);
        let transform = new Uint8Array(decodeBuffer);
        // 格式化数据
        let dataViewData = dingdingTool(undefined).formatterData(transform, undefined);
        let dataView = new DataView(dataViewData.buffer, 0, dataViewData.buffer.byteLength);
        const textDecoder = new TextDecoder();
        let result = textDecoder.decode(dataView);
        return [undefined, result];
    } catch (error) {
        return [new InsideErr(error as any), undefined];
    }
}

async function toRequestSecretData(
    secretInfo: { salt: string; secret: string },
    ecpOssUrl: string
): Promise<[BaseErr?, any?]> {
    let { salt, secret } = secretInfo || {};
    if (util.nilValue(salt)) {
        return [new ParamErr(" secretInfo的 salt "), undefined];
    }
    if (util.nilValue(secret)) {
        return [new ParamErr(" secretInfo的 secret "), undefined];
    }
    if (util.nilValue(ecpOssUrl)) {
        return [new ParamErr(" ecpOssUrl "), undefined];
    }
    let [file_err, file_data] = await requestData(ecpOssUrl);
    if (!util.nilValue(file_err)) {
        return [file_err, undefined];
    }
    // 有数据了, 要 解密到 内容
    let [content_err, content_data] = await handleResultBuffer(file_data, salt, secret);
    if (!util.nilValue(content_err)) {
        return [content_err, undefined];
    }
    // 格式化数据
    return formatterContent(content_data);
}

export { toRequestSecretData };
